const BaseController = require("./base/base");
const Result = require("../utils/result");
const RulesModel = require("../model/rules");
class UsersController extends BaseController {
  constructor() {
    super();
    this.key = "xiaohuai";
  }
  // 获取规则列表
  findRulesList(req, res, next) {
    setTimeout(async () => {
      try {
        let { pagesize=5, page = 1, text = '' } = req.query;
        pagesize *= 1
        page *= 1
        // 页码对应的数据查询开始位置
        const _filter = { text: { $regex: text, $options: 'i' } }
        let start = (page - 1) * pagesize;
        let list = await RulesModel.find(_filter).limit(pagesize).skip(start)
        let total = await RulesModel.countDocuments()
        res.json(Result.ok("success", { total, list }));
      } catch (err) {
        res.json(Result.error(err));
      }
    })
  }
  // 增加规则
  insert(req, res, next) {
    setTimeout(async () => {
      try {
        let { text = '', content = '', add_time } = req.body;
        if (!(text && content)) return res.json(Result.fail("请填写完整信息"));
        let ret = await RulesModel.findOne({ text });
        if (ret) return res.json(Result.fail("规则名已存在"));
        ret = await RulesModel.create({ text, content, add_time });
        res.json(!ret._id ? Result.fail("添加失败") : Result.ok("添加成功", ret))
      } catch (err) {
        res.json(Result.error(err));
      }
    })
  }
  // 获取单个规则信息
  findById(req, res, next) {
    setTimeout(async () => {
      try {
        let { id } = req.params;
        let ret = await RulesModel.findOne({ _id: id });
        res.json(Result.ok("success", ret));
      } catch (err) {
        res.json(Result.error(err));
      }
    })
  }
  // 修改规则信息
  updaterule(req, res, next) {
    setTimeout(async () => {
      try {
        const { id } = req.params;
        let ret = await RulesModel.updateOne({ _id: id }, req.body);
        if (ret.modifiedCount == 0) res.json(Result.fail("修改失败", ret))
        res.json(Result.ok("修改成功", ret));
      } catch (err) {
        res.json(Result.error(err));
      }
    })
  }
  // 删除规则
  delById(req, res, next) {
    setTimeout(async () => {
      try {
        const { id } = req.params;
        let ret = await RulesModel.deleteOne({ _id: id });
        res.json(!ret.deletedCount ? Result.fail("删除失败") : Result.ok("删除成功", ret))
      } catch (err) {
        res.json(Result.error(err));
      }
    })
  }
}
module.exports = new UsersController().resolve();